package com.itheima.jobs;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.pojo.OrderSetting;
import com.itheima.service.OrderSettingService;
import com.itheima.utils.DateUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Component;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.util.Date;
import java.util.List;

/*定时清理预约设置数据*/
@Component
public class RegularlyCleanUpPackageDataJob {

    @Reference
    private OrderSettingService orderSettingService;

    /*定时清理预约设置数据*/
    public void regularlyCleanUpPackageData() {
        try {
            //获取本月一月
            String firstDay4ThisMonth = DateUtils.parseDate2String(DateUtils.getFirstDay4ThisMonth());
            List<OrderSetting> orderSettingList = orderSettingService.regularlyCleanUpPackageData(firstDay4ThisMonth);
              //写标题目录
            XSSFWorkbook xssfWorkbook = new XSSFWorkbook();
            XSSFSheet sheetAt = xssfWorkbook.createSheet("预约设置");
            XSSFRow row = sheetAt.createRow(0);
            row.createCell(0).setCellValue("ID");
            row.createCell(1).setCellValue("预约日期");
            row.createCell(2).setCellValue("可预约数量");
            row.createCell(3).setCellValue("已预约数量");
            //判断是否有值
            if (orderSettingList != null && orderSettingList.size() > 0) {
                int count = 1;
                for (OrderSetting orderSetting : orderSettingList) {
                    XSSFRow rowCount = sheetAt.createRow(count);
                    rowCount.createCell(0).setCellValue(orderSetting.getId() + "");
                    rowCount.createCell(1).setCellValue(DateUtils.parseDate2String(orderSetting.getOrderDate()));
                    rowCount.createCell(2).setCellValue(orderSetting.getNumber() + "");
                    rowCount.createCell(3).setCellValue(orderSetting.getReservations() + "");
                    count++;
                }
            }
            //获取下载路径,将删除的内容以xls文件存储
            File file = new File("health_jobs");
            String[] split = file.getAbsolutePath().split("health_jobs");
            String name = firstDay4ThisMonth + "&" + DateUtils.parseDate2String(new Date(), "yyyy-MM-dd&HH-mm-ss").substring(11);
            String path = split[0] + name + ".xlsx";
            BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(new File(path)));
            xssfWorkbook.write(out);
            out.flush();
            out.close();
            xssfWorkbook.close();
            System.out.println("【定时任务】" + DateUtils.parseDate2String(new Date(), "yyyy-MM-dd HH:mm:ss") + "开始清理预约设置数据");
            //清理预约设置数据
            orderSettingService.deletePackageData(firstDay4ThisMonth);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
